<template>
  <div class="box">
    <el-button type="primary" class="mb-10" icon="el-icon-circle-plus-outline" @click="addRole">新增角色</el-button>
    <!--table-->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
      class="table"
      stripe
      header-cell-class-name="table-header">
      <el-table-column prop="key" label="角色key" width="220"></el-table-column>
      <el-table-column prop="name" label="角色名称" width="220"></el-table-column>
      <el-table-column prop="remark" label="角色描述"></el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template v-slot="scope">
          <el-button type="primary" size="mini" @click="editRole(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" :disabled="scope.row.key === 'admin'" @click="deleteRole(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--角色的弹窗-->
    <el-dialog
      :visible.sync="roleVisible"
      destroy-on-close
      top="5vh"
      center
      :title="roleTypeName">
      <el-form
        ref="form"
        :model="role"
        :rules="rules"
        :disabled="role.key === 'admin'"
        label-width="100px">
        <el-form-item label="角色key：" prop="key">
          <el-input v-model="role.key" placeholder="角色key" />
        </el-form-item>
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="role.name" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="角色描述：" prop="remark">
          <el-input
            v-model="role.remark"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="角色描述"
          />
        </el-form-item>
        <el-form-item label="权限：" prop="routes">
          <template slot="label">
            <span class="red-start-4">*</span>
            <span>权限：</span>
          </template>
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            default-expand-all
            :default-checked-keys="role.routes"
            node-key="id"
            class="permission-tree" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelRole">取消</el-button>
        <el-button type="primary" :disabled="role.key === 'admin'" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { adminRoutes } from '@/router/temp-routes'

const defaultRole = {
  key: '',
  name: '',
  remark: '',
  routes: []
}

export default {
  name: 'Role',
  data() {
    return {
      loading: false,
      tableData: [],
      roleVisible: false,
      routesData: adminRoutes,
      role: Object.assign({}, defaultRole),
      rules: {
        key: [{ required: true, message: '请输入key', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
      },
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    roleTypeName() {
      return this.role.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    // 获取角色的信息列表
    getTableData() {
      this.loading = true
      setTimeout(() => {
        this.tableData = [
          {
            id: '1001',
            key: 'admin',
            name: '超级管理员',
            remark: '超级管理员。可以查看所有页面',
            routes: ['100101', '100102', '100103', '100104', '10020101', '10020102', '100202', '100301',
              '100302', '100303', '100304', '100401', '100402', '1005', '1006', '1007']
          },
          {
            id: '1002',
            key: 'ordinary',
            name: '普通角色',
            remark: '可以查看除权限页,组件-小组件以外的所有页',
            routes: ['100101', '100104', '10020101', '10020102', '100202', '100301', '100302', '1005', '1006']
          }
        ]
        this.loading = false
      }, 300)
    },
    // 新增角色
    addRole() {
      this.role = defaultRole
      this.roleVisible = true
    },
    // 编辑角色
    editRole(row) {
      this.role = deepClone(row)
      this.roleVisible = true
    },
    // 删除角色
    deleteRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
        center: true
      }).then(() => {
        console.log('deleteRole', id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
      })
    },
    // 取消角色的弹窗操作，顺便清空数据
    cancelRole() {
      this.roleVisible = false
      this.role = defaultRole
    },
    // 角色弹窗，确认操作
    confirmRole() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 获取所有选中的结点
          const checkedKeys = this.$refs.tree.getCheckedKeys()
          // 权限为必填
          if (checkedKeys?.length === 0) {
            this.$message.error('请选择权限')
            return
          }
          // 在选中的结点里面，查询当前的结点是否是叶子结点
          let arr = []
          this.$nextTick(() => {
            for (let i = 0; i < checkedKeys.length; i++) {
              let node = this.$refs.tree.getNode(checkedKeys[i])
              // 是叶子结点提取出来
              if (node.isLeaf) {
                arr.push(node.data.id)
              }
            }
          })
          this.role.routes = arr
          console.log('this.role', this.role)
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
